package com.etc.controller;

import com.etc.entity.Question;
import com.etc.entity.Questionnaire;
import com.etc.entity.User;
import com.etc.mapper.QuestionnaireMapper;
import com.etc.service.QuestionnaireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/Question")
public class QuestionController {

    @Autowired
    QuestionnaireService questionaire;

    @Autowired
    QuestionnaireMapper questionnaireMapper;

    @RequestMapping("/qu")
    public String question(){
        questionnaireMapper.update(1,"213",5);
        return "index";
    }
    @RequestMapping("/queryAll")
    public  String queryAll(Model model){
        List<Question> queryquestion = questionaire.queryquestion();
        model.addAttribute("questionnaires",queryquestion);
        return "Questionnaire";
    }





    @RequestMapping("/form")
    public String form(@RequestParam HashMap<String,String> q, HttpSession session){
        String name =null;
        int userid=1;
        User user = (User) session.getAttribute("user");
       if(user!=null){
           name=user.getUsername();
           userid=user.getUserid();
       }

        List<Integer> list = new ArrayList<Integer>();
        List<Questionnaire> admin = questionnaireMapper.querybyname(name);
        int size = admin.size();
        System.out.println(size);
        for(Questionnaire a:admin){
            list.add(a.getQuestionnaire_id());
            System.out.println(a.getQuestionnaire_id());
        }
        int id=0;
        Set<String> strings = q.keySet();
        Iterator<String> it = strings.iterator();
        while(it.hasNext()){
            String key =it.next();
            String k="";
            String value = q.get(key);
            String v="";
            char[] chars = key.toCharArray();
            for(char c :chars){
                if(Character.isDigit(c)){
                    k=String.valueOf(c);
                }
            }
            if(value.equals("2")){
                v="是";
            }else{
                v="否";
            }
            Integer ke= Integer.valueOf(k);
            if (size==0){
                if(name==null){
                    questionaire.insertQ(ke,v);
                }else{
                    questionnaireMapper.insertN(ke,v,userid);
                }
            }else{
                System.out.println("----"+list.get(id));
                questionnaireMapper.update(ke,v,list.get(id));
                id++;
            }
            System.out.println("key=="+k+"===value=="+v);
        }
        return "redirect:/user/login";
    }
}
